package cn.snailhd.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

public class FileDownloadManage {
	private int length = 1024*512;
	private Logger log = Logger.getLogger(this.getClass().getName());
	
	public static void main(String[] args) throws IOException {
	/*	String url="http://image.baidu.com/search/down?tn=download&"
				+ "ipn=dwnl&word=download&ie=utf8&fr=result&url=http"
				+ "%3A%2F%2Fr001.joyme.com%2Fr001%2Fimage%2F2013%2F1"
				+ "1%2F87%2Fd8c3b10905e02044440a7f506b8be1497b49.jpg"
				+ "&thumburl=http%3A%2F%2Fimg1.imgtn.bdimg.com%2Fit%2"
				+ "Fu%3D127323536%2C931889285%26fm%3D21%26gp%3D0.jpg";*/
		
		
		String url = "http://v.uzzf.com//fla/FlashCC2015_Setup.zip";
		FileDownloadManage fd = new FileDownloadManage();
		long begin = System.currentTimeMillis();
		fd.manage(1, url, "D:\\33333.zip");
		long end = System.currentTimeMillis();
		System.out.println(end-begin);
	}
	
	public int getFileSize(String url) throws IOException{		
		HttpRequest request = new HttpRequest(url);
		HttpURLConnection  connection = request.getConnection();
		int realSize = connection.getContentLength();
		return realSize;		
	}
	
	public void  manage(int poolCount,String url,String file) throws IOException{
		int size = getFileSize(url);
		System.out.println("size:"+size/1024+"kb");
		int num = size/length;
		CountDownLatch end = new CountDownLatch(num+1);
		
		ExecutorService exec = Executors.newFixedThreadPool(poolCount);
		
		for(int i=0;i<num+1;i++){
			exec.execute(new FileDownload(url, file, length*i, length, end));
		}
		
		exec.shutdown();
		try {
			end.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("end!!!");
		
	}

}
